package com.zhlq.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.zhlq.log.bean.Visit;
import com.zhlq.log.service.LogService;
import com.zhlq.util.SpringContext;

/**
 * 访问操作过滤器
 */
public class ObserveFilter implements Filter {
	
	private static final String IGNORES = "ignores";
	private Set<String> ignores = new HashSet<String>();
	
	private LogService logService;

	/**
	 * 销毁处理
	 */
	public void destroy() {
		// 不需要处理
	}

	/**
	 * 转发前处理
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest requestHttp = (HttpServletRequest) request;
        String path = requestHttp.getServletPath();
        Iterator<String> it = ignores.iterator();
        boolean flag = true;
        while (it.hasNext()){
        	String regex = it.next();
        	if(Pattern.compile(regex).matcher(path).find()){
                flag = false;
                break;
        	}
        }
        if(flag){
    		Date date = new Date();
//    		path = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS").format(date);
//			path = ConfigUtil.get("serializeRoot")+File.separator+path;
//			FileUtil.write(JsonUtil.toJson(request), path);
    		Visit visit = logService.getVisit(requestHttp);
//    		visit.setPath(path);
    		visit.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(date));
    		logService.create(visit);
        }
		chain.doFilter(request, response);
	}

	/**
	 * 初始化处理
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		if(null == logService){
			logService = (LogService) SpringContext.getBean("logService");
		}
		String ignoreString = fConfig.getInitParameter(IGNORES);
		if(null == ignoreString){
			return ;
		}
		// 以英文逗号作为分隔符
		String[] tmps = ignoreString.split(",");
		if(null!=tmps && tmps.length>0){
			for(int i = 0; i < tmps.length; i++){
				if(null!=tmps[i]){
					String tmp = tmps[i].replaceAll("[\\s|\t|\r|\n]", "");
					if(null!=tmp && !"".equals(tmp)){
						ignores.add(tmp);
					}
				}
			}
		}
	}

}
